package org.codehaus.activemq.message;

import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public abstract class AbstractPacketReader
  implements PacketReader
{
  public boolean canRead(int packetType)
  {
    return getPacketType() == packetType;
  }

  protected String readUTF(DataInput dataIn)
    throws IOException
  {
    return dataIn.readUTF();
  }

  protected Object readObject(DataInput dataIn)
    throws IOException
  {
    int dataLength = dataIn.readInt();
    if (dataLength > 0) {
      byte[] data = new byte[dataLength];
      dataIn.readFully(data);
      ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
      ObjectInputStream objIn = new ObjectInputStream(bytesIn);
      try {
        return objIn.readObject();
      }
      catch (ClassNotFoundException ex) {
        throw new IOException(ex.getMessage());
      }
    }
    return null;
  }

  public void buildPacket(Packet packet, DataInput dataIn)
    throws IOException
  {
    packet.setId(readUTF(dataIn));
    packet.setReceiptRequired(dataIn.readBoolean());
  }

  public Packet readPacketFromByteArray(byte[] data)
    throws IOException
  {
    ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
    DataInputStream dataIn = new DataInputStream(bytesIn);
    Packet packet = createPacket();
    buildPacket(packet, dataIn);
    return packet;
  }
}